
<template>
  <div style="background: #ececec; padding: 30px">
    <a-row :gutter="16">
      <a-col :span="8">
        <a-card title="字典分类" :bordered="false">
          <template #extra
            ><a-button class="user-btn" type="primary" @click="onAdd">添加</a-button></template
          >
          <a-input-search
            style="margin-bottom: 8px"
            placeholder="Search"
            @change="onChange"
          />
          <a-tree
            v-if="treeData.length > 0"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :defaultExpandAll="true"
            @expand="onExpand"
            @select="onSelect"
          >
            <template #title="{ title }">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{
                  title.substr(title.indexOf(searchValue) + searchValue.length)
                }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card title="分类信息" :bordered="false">
          <a-form
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            style="margin-top: 20px"
          >
            <a-form-item label="上级分类" name="higherId">
              <a-tree-select
                v-model:value="form.higherId"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择上级"
                tree-default-expand-all
                @select="onHigherIdSelect"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item label="分类名称" name="name">
              <a-input
                type="text"
                v-model:value="form.name"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item label="备注" name="remark">
              <a-textarea v-model:value="form.remark" />
            </a-form-item>
            <a-form-item label="排序号" name="sequence">
              <a-input
                type="number"
                v-model:value="form.sequence"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item>
              <a-checkbox @change="onChange" v-model:checked="form.enabled">
                启用
              </a-checkbox>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button class="user-btn" type="primary" @click="onSubmit"> 保存 </a-button>
              <a-button
                class="user-btn"
                @click="resetForm"
                v-if="!addFlag"
              >
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import {
  sysCategoryAllAPI,
  sysCategoryInfoAPI,
  sysCategoryModifyAPI,
  sysCategoryAddAPI,
} from "../../api/api";
import { message } from "ant-design-vue";
export default {
  data() {
    return {
      treeData: [],
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      defaultExpandAll: true,
      dataList: [],
      form: {
        id: null,
        name: "",
        remark: "",
        higherId: undefined,
        sequence: "",
        enabled: false,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.fetch();
  },
  methods: {
    fetch(params = {}) {
      //console.log("params:", params);
      this.loading = true;
      sysCategoryAllAPI(params).then((res) => {
        this.loading = false;
        if (res.data.succeeded) {
          var rootNode = {};
          (rootNode.id = 0), (rootNode.name = "根节点");
          rootNode.remark = "根节点";
          rootNode.higherId = -1;
          rootNode.sequence = 1;
          rootNode.enabled = true;
          res.data.data.push(rootNode);
          this.treeData = this.convertToTreeData(res.data.data, -1);
        } else {
          message.error(res.data.errors);
        }
      });
    },
    convertToTreeData(data, higherId) {
      const result = [];
      let temp = [];
      for (let i = 0; i < data.length; i++) {
        data[i].higherId = data[i].higherId == null ? 0 : data[i].higherId;
        if (data[i].higherId === higherId) {
          const key = data[i].id;
          this.expandedKeys.push(key);
          this.dataList.push({ key, title: data[i].name });
          let item = {};
          item.key = data[i].id;
          item.value = data[i].id;
          item.title = data[i].name;
          item.isLeaf = true;
          temp = this.convertToTreeData(data, data[i].id);
          if (temp.length > 0) {
            item.isLeaf = false;
            item.children = temp;
          }
          result.push(item);
        }
      }
      return result;
    },
    onSelect(selectedKeys, info) {
      if (selectedKeys !== undefined && selectedKeys.length > 0) {
        var selectId = selectedKeys[0];
        if (selectId === undefined || selectId === 0) {
          message.warning("根节点，不可修改");
          return;
        }
        this.loading = true;
        if (this.form.id !== selectId && selectId !== undefined) {
          sysCategoryInfoAPI(selectId).then((res) => {
            this.loading = false;
            this.form.id = res.data.data.id;
            this.form.name = res.data.data.name;
            this.form.remark = res.data.data.remark;
            this.form.higherId = res.data.data.higherId;
            this.form.enabled = res.data.data.enabled;
            this.form.sequence = res.data.data.sequence;
          });
        }
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    getParentKey(key, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some((item) => item.key === key)) {
            parentKey = node.key;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    onChange(e) {
      var value = e.target.value;
      var tData = this.treeData;
      this.expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, tData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      console.log(this.expandedKeys);
      this.searchValue = value;
      this.autoExpandParent = true;
    },
    onHigherIdSelect(value, node, extra) {
      this.form.higherId = value;
    },
    onSubmit() {
      this.$refs.ruleForm
        .validate()
        .then(() => {
          var model = JSON.parse(JSON.stringify(this.form));
          model.higherId = model.higherId === 0 ? null : model.higherId;
          this.loading = true;
          if (this.form.id == null) {
            //新增
            Reflect.deleteProperty(model, "id");
            sysCategoryAddAPI(model).then((res) => {
              this.loading = false;
              if (res.data.succeeded) {
                this.form.id = res.data.data.id;
                this.form.name = res.data.data.name;
                this.form.remark = res.data.data.remark;
                this.form.higherId = res.data.data.higherId;
                this.form.enabled = res.data.data.enabled;
                this.form.sequence = res.data.data.sequence;
                this.fetch();
                message.success("保存成功！");
              } else {
                message.error(res.data.errors);
              }
            });
          } else {
            //修改
            var cateId = model.id;
            Reflect.deleteProperty(model, "id");
            sysCategoryModifyAPI(cateId, model).then((res) => {
              if (res.data.succeeded) {
                this.fetch();
                message.success("保存成功！");
              } else {
                message.error(res.data.errors);
              }
            });
          }
        })
        .catch((error) => {
          message.error(error);
        });
    },
    onAdd() {
      this.$refs.ruleForm.resetFields();
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>
<style lang="scss">
.user-btn {
  margin: 5px;
}
</style>